
<template>
  <div class="dt-select-app">
    <!-- 选人弹框 -->
    <dt-dialog :title="title" append-to-body :visible.sync="open"
               width="1000px" @comfirmBtn="submitForm" @closeDialog="cancel">
      <div slot="content" class="dt-select-app-body">
        <el-row>
          <!-- 树结构 -->
          <el-col v-if="appType === 'allApp'" :span="4" :xs="24">
            <div class="mainbox-left">
              <div class="box-card">
                <el-tree
                  ref="tree"
                  :style="{'--lightOpacity':lightTheme}"
                  class="left-tree"
                  :empty-text="$store.getters.dataText"
                  :data="treeList"
                  :props="defaultProps"
                  default-expand-all
                  highlight-current
                  :node-key="defaultProps.id"
                  expand-on-click-node
                  :current-node-key="currentKey"
                  :filter-node-method="filterNode"
                  @node-click="handleNodeClick"
                >
                  <div slot-scope="{ node, data }" class="custom-tree-node">
                    <!-- <el-tooltip class="item" effect="dark" :content="data.typeName" placement="right-start">
                      <span class="tree-name">{{ data.typeName || ellipsis(8) }}</span>
                    </el-tooltip> -->
                    <DtOverTooltip :content="data.typeName" />
                  </div>
                </el-tree>
              </div>
            </div>
          </el-col>
          <!-- 主内容 -->
          <el-col :span="appType === 'allApp' ? 14 : 18" :xs="24" style="padding-left: 0px">
            <div class="none2-border3 userlist mainbox">
              <dt-table
                ref="table"
                v-loading="loading"
                :table-opts="tableOpts"
                :pagination-data="{
                  total:total,
                  queryParams:queryParams
                }"
                @pagination="getList"
                @searchChange="handleQuery"
                @searchReset="handleReset"
                @handleSelectionChange="handleSelectionChange"
                @radioChange="rowClick"
              />
            </div>
          </el-col>
          <!-- 已选列表 -->
          <el-col :span="6" :xs="24">
            <div class="mainbox-left">
              <div class="box-card">
                <div style="display: flex;justify-content: space-between;align-items: center;">
                  <div class="num">已选（{{ newMultipleSelectionChangeData.length }}）</div>
                  <el-button v-if="isMultiple" type="text" @click="clearAll()">清空</el-button>
                </div>
                <div class="app_type_list">
                  <div
                    v-for="(item,index) in newMultipleSelectionChangeData"
                    :key="index"
                    class="already"
                  >
                    {{ item.appName }}<span class="cancle"><i class="el-icon-close el-icon--right" @click="handleCheckedChange(item)" /></span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </dt-dialog>
  </div>
</template>
<script>
import clientManageApi from '@/framework/api/clientManage'
import emitter from 'element-ui/src/mixins/emitter'
// 自定义表单提交不校验问题 结合  this.dispatch('ElFormItem', 'el.form.change', newVal)
export default {
  name: 'DtSelectApp',
  filters: {
    ellipsis(value, k) {
      if (!value) return ''
      if (value.length > k) {
        return `${value.slice(0, k)}...`
      }
      return value
    }
  },
  mixins: [emitter],
  props: {
    // 是否多选
    isMultiple: {
      type: Boolean,
      default: true
    },
    appType: {
      type: String, // allApp 含应用类型的所有应用    other 其他应用  需要传入provider
      default: 'allApp'
    },
    provider: { // 传入方法
      type: Function,
      default() { }
    },
    condition: { // 传入参数
      type: Object,
      default: () => {
        return {}
      }
    },
    // 值
    value: { // 选中appIds字符串 '1,2,3'
      type: String,
      default: ''
    },
    isDisabledSelect: { // 是否禁用已选人员
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 是否显示弹出层
      title: '选择应用',
      // 遮罩层
      loading: false,
      open: false,
      appTypeItemSelect: {},
      tree: [],
      multipleSelectionChangeData: [], // 多选选中数据
      // 总条数
      total: 0,
      queryParams: {
        appType: '',
        statusFlag: 1,
        appName: '',
        pageNo: 1,
        pageSize: 10
      },
      tableOpts: {
        highlightCurrentRow: !this.isMultiple || false,
        rowKey: 'appCode',
        toolbarBtn: [
        ],
        firstTableCol: {
          select: this.isMultiple,
          width: 55,
          type: 'selection',
          // isRowClickSelect: true,
          bind: {
            // selectable: this.selectEnable
            selectable: this.selectableChange
          }
        },
        indexTableCol: {
          label: '序号',
          width: 70
        },
        tableCol: [
          {
            prop: 'appName',
            label: '应用名称',
            show: true,
            search: true,
            labelWidth: '70px'
          },
          {
            prop: 'appCode',
            label: '应用编码',
            show: true
          },
          {
            prop: 'appSort',
            label: '排序',
            show: true
          },
          {
            prop: 'remark',
            label: '描述',
            show: true
          }
        ],
        tableData: []
      },
      treeList: [],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      currentKey: '',
      selectAppData: [], // 父组件已选应用
      selectApp: [],
      newMultipleSelectionChangeData: []
    }
  },
  computed: {
    lightTheme() {
      return `${this.$store.state.settings.theme}19`
    }
  },
  methods: {
    // 是否可选
    selectableChange(row, index) {
      return !this.multipleSelectionChangeData.some((item) =>
        item.appId === row.appId)
    },
    // 打开弹窗
    openSelect(selectAppData) {
      this.selectAppData = selectAppData
      this.open = true
      if (this.appType !== 'other') {
        this.getTypeList()
      } else {
        this.getList()
      }
      this.dealSelectApp()
    },
    selectEnable(row) {
      return false
    },
    // 回显多选选中数据
    dealSelectApp() {
      if (this.appType === 'other') {
        this.newMultipleSelectionChangeData = this.selectAppData
        this.$nextTick(() => {
          if (this.isMultiple) {
            this.newMultipleSelectionChangeData.forEach((item) => {
              this.$refs.table.toggleRowSelection(item, true)
            })
          } else {
            this.handleTableRadioHighRow(this.newMultipleSelectionChangeData[0])
          }
        })
      } else {
        if (this.selectAppData && this.selectAppData.length > 0) {
          const appCodes = this.selectAppData.map((item) => {
            return item.appCode
          }).join(',')
          clientManageApi.getPlatAppListByAppCodes(appCodes).then((res) => {
            this.multipleSelectionChangeData = res.data
            this.multipleSelectionChangeData.forEach((item) => {
              this.$refs.table.toggleRowSelection(item, true)
            })
          })
        }
        // 租户和平台管理员的应用列表不一致，通过appCodes是的应用数据一致
      }
    },
    // 过滤树节点
    filterNode(value, data) {
      if (!value) return true
      return data.typeName.indexOf(value) !== -1
    },
    // 获取应用类型
    getTypeList() {
      clientManageApi.sysAppType().then((res) => {
        this.treeList = [{
          typeName: '全部',
          children: (res.data || []).map((item) => {
            return { ...item, children: [] }
          }),
          id: ''
        }]
        this.currentKey = this.treeList[0].id
        this.handleNodeClick(this.treeList[0])
      })
    },
    // 点击树结点
    handleNodeClick(row) {
      this.queryParams.appType = row.id
      this.getList()
    },
    // 获取应用列表
    async  getList() {
      this.loading = true
      if (this.appType === 'allApp') {
        clientManageApi.sysApp(this.queryParams).then((res) => {
          this.tableOpts.tableData = res.data.rows
          this.total = res.data.totalRows
          this.loading = false
        })
      } else { // 来源应用
        const res = await this.provider(Object.assign({}, this.condition, this.queryParams))
        this.tableOpts.tableData = res.data.rows
        this.total = res.data.totalRows
        this.loading = false
      }
    },
    // 搜索
    handleQuery(formModel) {
      this.queryParams = Object.assign(this.queryParams, formModel)
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    handleReset() {
      this.queryParams = {
        appType: this.queryParams.appType,
        appName: '',
        pageNo: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      if (this.appType === 'allApp') {
        // 租户下设置应用需处理右侧已选为只有新增的
        this.newMultipleSelectionChangeData = val.filter((item) =>
          !this.multipleSelectionChangeData.some((it) => item.appId === it.appId))
      } else {
        // 数据同步 右侧应用为所有数据
        this.newMultipleSelectionChangeData = val
      }
    },
    // 删减
    handleCheckedChange(val) {
      if (this.isMultiple) {
        const deleteList = this.tableOpts.tableData.filter((item) => {
          return item.appCode === val.appCode
        })
        this.$refs.table.toggleRowSelection(deleteList.length ? deleteList[0] : val, false)
      } else {
        this.newMultipleSelectionChangeData = this.newMultipleSelectionChangeData.filter((item) => item.appId !== val.appId)
        this.handleTableRadioHighRow()
      }
    },
    /** 保存选中 */
    submitForm() {
      if (this.appType === 'allApp') {
        this.multipleSelectionChangeData = this.multipleSelectionChangeData.concat(this.newMultipleSelectionChangeData)
      } else {
        this.multipleSelectionChangeData = this.newMultipleSelectionChangeData
      }
      const appIds = this.multipleSelectionChangeData.map((item) => {
        return item.appId
      }).join(',')

      this.$emit('saveData', appIds, this.multipleSelectionChangeData)
      this.dispatch('ElFormItem', 'el.form.change', appIds)
    },
    // 取消/关闭按钮
    cancel() {
      this.queryParams.appName = ''
      this.$refs.table?.DtSearchReset()
      // 清空选中
      this.$refs.table?.clearSelection()
      this.multipleSelectionChangeData = []
      this.open = false
    },
    handleTableRadioHighRow(row) {
      if (row) {
        this.$refs.table.setCurrentRow(row, true) // 高亮某一行
      } else {
        this.$refs.table.setCurrentRow() // 取消高亮
      }
    },
    rowClick(row, column, event) {
      // this.multipleSelectionChangeData = [row]
      this.newMultipleSelectionChangeData = [row]
    },
    // 清空按钮
    clearAll() {
      if (this.appType === 'allApp') {
        if (this.newMultipleSelectionChangeData && this.newMultipleSelectionChangeData.length > 0) {
          this.newMultipleSelectionChangeData.forEach((row) => {
            this.$refs.table?.toggleRowSelection(row, false)
          })
        }
      } else {
        this.$refs.table?.clearSelection()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.dt-select-app{

  .select-person-click{
    border: 1px #c0c4cc solid;
    border-radius: 5px;
    cursor: pointer;
    // min-height:40px;
    width: 100%;
    height:100%;
    padding: 0px 8px 0 8px;
    // line-height: 28px;
    margin: auto;
    min-height: 36px;
    line-height: 36px;
    min-width: 200px;
    > div{
      margin: auto;
    }
    .el-tag {
      margin-right: 5px;
      margin-bottom: 4px;
    }
  }
     .isDisabled{
      background-color: #F5F7FA !important;
      border-color:#E4E7ED !important;
      color: #C0C4CC !important;
      cursor: not-allowed !important;
    }
  .plactext{
    color: #DCDFE6;
  }
}
::v-deep .el-dialog__header{
  padding-bottom: 5px !important;
}
::v-deep .dt-select-app-body {
  flex: 1;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  >.el-row {
    display: flex;
    flex: 1;
    flex-wrap: wrap;

    >.el-col {
      .mainbox-left {
        height: 100%;
        display: flex;
        flex-direction: column;

        flex: 1;
        border-radius: 5px;

        // background: #f8f9fa;
        >.box-card {
          height: 100%;
          min-height: 400px;
          border-radius: 5px;
          display: flex;
          flex-direction: column;
          padding: 16px;
          margin: 16px;
          margin-right: 0;
          // margin-right: 2px;
          background: #fff;
          box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
            0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 0px 4px 0px rgba(0, 0, 0, 0.08);

          .el-table {
            flex: 1;
          }
        }

        .already{

          display: flex;
          align-items: center;
          margin: 8px 0 0 0px;
          cursor: pointer;
          justify-content: space-between;
        }
        .already:hover{
          color:rgb(52, 97, 255);
        }
        .num{
          color: #9E9E9E;
          // margin-left: 14px;
          // margin-bottom: 16px;
        }
      }
      .mainbox-left{
        .box-card{
          margin-left: 0;
        }
      }
    }
  }

  .mainbox {
    height: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
    // max-height: calc(100vh - 100px);
    // background: #fff;
    border-radius: 5px;
    padding: 16px;
    // padding-left: 0px;
    // background: #f8f9fa;

    //搜索区域
    .filter-container {
      background: #fff;
      border-radius: 4px;
      margin-bottom: 16px;
      padding: 20px 16px;
      padding-bottom: 0;
      display: flex;
      justify-content: flex-start;
      box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
        0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 0px 4px 0px rgba(0, 0, 0, 0.08);
      flex-wrap: wrap;

      .filter-item {
        display: inline-block;
        vertical-align: middle;
        // margin-left: 10px;
      }

      .el-form {
        .el-form-item {
          // margin-bottom: 0;
        }
      }

      .el-button {
        align-self: flex-start;
        margin-bottom: 16px;
      }
    }

    //表格区域
    .table-container {
      display: flex;
      border-radius: 4px;
      flex-direction: column;
      background: #fff;
      padding: 16px;
      flex: 1;
      box-shadow: 0px 4px 8px 2px rgba(0, 0, 0, 0.04),
        0px 2px 6px 0px rgba(0, 0, 0, 0.06), 0px 0px 4px 0px rgba(0, 0, 0, 0.08);

      //表格操作区域
      .table-opt-container {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        .el-button{
          margin-bottom: 8px;
        }
      }

      .el-table {
        flex: 1;

        .cell {
          padding-left: 16px !important;
          padding-right: 16px !important;

        }
      }
    }

    .demo-form-inline {
      display: flex;
      justify-content: flex-end;
    }

    .el-table {
      // min-height: calc(100vh - 270px);
      // max-height: calc(100vh - 270px);
      // overflow: scroll;
    }
    }

}
.custom-tree-node{
    display: flex;
    color: #131314;
    font-size: 14px !important;
    align-items: center;
    overflow: hidden;
    width: 100%;
    .tree-name{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex:1;
    }
  }
::v-deep .el-tree-node__content {
    height: 100%;
    // align-items: start;
  }
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
::v-deep .el-tree-node .el-tree-node__content {
    padding-left: 0 !important;
}

</style>
<style lang="scss">
  .el-form-item.is-error .dt-select-app .el-input__inner{
    border-color: #DCDFE6;
  }
  .is-error{
    .dt-select-app{
      .select-person-click{
        border-color: #F56C6C !important;
      }
    }
  }
</style>
